import struct, socket, time, urllib, urllib2, hashlib
host = "192.168.0.100"
port = 25565
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

logindata = {'user':'SeR', 'password':'1234', 'version':'29'}
data = urllib.urlencode(logindata)
'''print('Sending data to login.minecraft.net...')
req = urllib2.Request('https://login.minecraft.net', data)
response = urllib2.urlopen(req)
returndata = response.read() 
returndata = returndata.split(":")
mcsessionid = returndata[3]
del req
del returndata
print("Session ID: " + mcsessionid)
'''

data = {'user':u'SeR','host':u'192.168.0.100','port':25565}
mcsessionid = logindata['user']
mcsessionid = hashlib.md5('SeR' + '1234')
mcsessionid = mcsessionid.hexdigest()

stringfmt = u'%(user)s;%(host)s:%(port)d'
string = stringfmt % data
structfmt = '>bh'
packetbytes = struct.pack(structfmt, 2, len(string))+string.encode('utf-16BE')
s.send(packetbytes)
connhash = s.recv(1024)

print ("Connection Hash: " + connhash)
print ('Sending data to http://session.minecraft.net/game/joinserver.jsp?user='+data['user']+'&sessionId=' + mcsessionid + '&serverId=' + connhash)
req = urllib.urlopen('http://session.minecraft.net/game/joinserver.jsp?user='+data['user']+'&sessionId=' + mcsessionid + '&serverId=' + connhash)

returndata = req.read()
if(returndata == 'OK'):
    print('session.minecraft.net says everything is okay, proceeding to send data to server.')
else:
    print('Oops, something went wrong.')

time.sleep(5)

# All above here works perfectly.
enc_user = data['user'].encode('utf-16BE')
#This line is probably where something's going wrong:
packfmt = '>bih{}shiibBB'.format(len(enc_user))
packetbytes = struct.pack(packfmt, 1, 23, len(data['user']), enc_user, 0, 0, 0, 0, 0, 0)
print(len(packetbytes))
print('Sending ' + packetbytes + ' to server.')
s.send(packetbytes)

while True:
    data = s.recv(1024)
    if data:
        print(data)
